<template>
  <div class="container mx-auto px-4 py-8">
    <div style="display: grid; justify-content: center; align-items: center;">
      <h1 class="text-2xl font-bold text-gray-800 mb-6">教职工管理</h1>
    </div>

    <!-- 添加查询输入框和查询按钮 -->
    <div class="mb-4 flex space-x-4">
      <input
          type="text"
          v-model="searchKeyword"
          placeholder="按姓名模糊查询"
          class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
      />
      <button
          @click="fetchEmployees"
          class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
      >
        查询
      </button>
    </div>
    
    <div class="action-bar bg-white rounded-lg shadow-md p-4 mb-6 flex justify-end">
      <button @click="showAddModal = true" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
        添加教职工
      </button>
    </div>
    
    <div class="overflow-x-auto">
      <table class="min-w-full bg-white rounded-lg overflow-hidden shadow-md">
        <thead class="bg-gray-800 text-white">
          <tr>
            <th class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider">工号</th>
            <th class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider">姓名</th>
            <th class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider">性别</th>
            <th class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider">出生日期</th>
            <th class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider">民族</th>
            <th class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider">邮箱</th>
            <th class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider">部门</th>
            <th class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider">职位</th>
            <th class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider">职称</th>
            <th class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider">操作</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-gray-200">
          <tr v-for="employee in employees" :key="employee.id">
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ employee.id }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ employee.name }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ employee.gender }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ employee.birthDate }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ employee.nation }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ employee.email }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
              {{ employee.department }}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
              {{ employee.position }}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
              {{ employee.title }}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
              <button @click="showEdit(employee)" class="text-indigo-600 hover:text-indigo-900 mr-3"> 操作</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div v-if="showEditView" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg p-6 w-full max-w-3xl mx-4">
        <div class="flex justify-center">
          <button
              @click="editEmployee(Employee); showEditView = false"
              class="text-indigo-600 hover:text-indigo-900 mr-3"
          >
            编辑
          </button>
          <button
              @click="deleteEmployee(Employee); showEditView = false"
              class="text-indigo-600 hover:text-indigo-900 mr-3"
          >
            删除
          </button>
        </div>
      </div>
    </div>

    <!-- 添加/编辑教职工模态框 -->
    <div v-if="showAddModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg p-6 w-full max-w-3xl mx-4">
        <h3 class="text-lg font-medium mb-4">{{ isEditing ? '编辑教职工' : '添加教职工' }}</h3>
        
        <form @submit.prevent="saveEmployee">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">工号</label>
              <input 
                type="text" 
                v-model="form.id"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                required
              >
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
              <input 
                type="text" 
                v-model="form.name" 
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                required
              >
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">性别</label>
              <select 
                v-model="form.gender" 
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                required
              >
                <option value="">请选择</option>
                <option value="男">男</option>
                <option value="女">女</option>
              </select>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">出生日期</label>
              <input 
                type="date" 
                v-model="form.birthDate" 
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
              >
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">民族</label>
              <input 
                type="tel" 
                v-model="form.nation"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
              >
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
              <input 
                type="email" 
                v-model="form.email" 
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
              >
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">部门</label>
              <select 
                v-model="form.department"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                required
              >
                <option value="">请选择</option>
                <option v-for="dept in departments" :key="dept.id" :value="dept.name">{{ dept.name }}</option>
              </select>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">职位</label>
              <select 
                v-model="form.position"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                required
              >
                <option value="">请选择</option>
                <option v-for="pos in positions" :key="pos.id" :value="pos.name">{{ pos.name }}</option>
              </select>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">职称</label>
              <select 
                v-model="form.title"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                required
              >
                <option value="">请选择</option>
                <option v-for="title in titles" :key="title.id" :value="title.name">{{ title.name }}</option>
              </select>
            </div>
          </div>
          <div class="flex justify-end space-x-3 mt-6">
            <button type="button" @click="showAddModal = false" class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
              取消
            </button>
            <button type="submit" class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
              保存
            </button>
          </div>

        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

const employees = ref([])
const departments = ref([])
const positions = ref([])
const titles = ref([])
const showAddModal = ref(false)
const isEditing = ref(false)
const form = ref({
  id: null,
  name: '',
  gender: '',
  birthDate: '',
  nation: '',
  email: '',
  department: null,
  position: null,
  title: null,
})
const showEditView = ref(false)
const Employee = ref(null)

const searchKeyword = ref('') // 添加查询关键词响应式变量

// 获取教职工列表
const fetchEmployees = async () => {
  try {
    let url = '/api/teacher'
    if (searchKeyword.value) {
      url += `?name=${searchKeyword.value}`
    }
    const response = await axios.get(url)
    employees.value = response.data.data
  } catch (error) {
    console.error('获取教职工列表失败:', error)
    alert('获取教职工列表失败，请稍后重试')
  }
}




const testEmail = async (email) => {
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return re.test(email)
}

// 添加/编辑教职工
const saveEmployee = async () => {
  try {
    if(!testEmail(form.value.email)) {
      alter("Email输入错误");
    }
    else if (isEditing.value) {
      await axios.put(`/api/teacher/${form.value.id}`, form.value)
    } else {
      await axios.post('/api/teacher', form.value)
    }
    showAddModal.value = false
    await fetchEmployees()
  } catch (error) {
    console.error('保存教职工失败:', error)
    alert('保存教职工失败，请稍后重试')
  }
}

// 编辑教职工
const editEmployee = (employee) => {
  form.value = {...employee}
  // 格式化日期
  if (employee.birthDate) {
    form.value.birthDate = new Date(employee.birthDate).toISOString().split('T')[0]
  }

  isEditing.value = true
  showAddModal.value = true
  Employee.value = null
}

const resetForm = () => {
  form.value = {
    id: null,
    name: '',
    gender: '',
    birthDate: '',
    nation: '',
    email: '',
    department: null,
    position: null,
    title: null,
  }
  isEditing.value = false
}

const deleteEmployee = async (employee) => {
  try{
    await axios.delete(`/api/teacher/${employee.id}`);
    await fetchEmployees()
  }
  catch(error) {
    alert('删除失败:' + error)
  }
}


const showEdit = (employee) => {
  Employee.value = employee
  showEditView.value = true
}

// 监听模态框显示状态，重置表单
const watchShowAddModal = () => {
  if (!showAddModal.value) {
    resetForm()
  }
}

onMounted(() => {
  fetchEmployees()
  // 获取部门列表
  axios.get('/api/dept')
    .then(response => {
      departments.value = response.data.data

    })
    .catch(error => {
      console.error('获取部门列表失败:', error)
      alert('获取部门列表失败，请稍后重试')
    })
  axios.get('/api/job-position')
  .then(response => {
    positions.value = response.data.data
  })
    .catch(error => {
      console.error('<UNK>:', error)
      alert('<UNK>')
    })
  axios.get('/api/title')
  .then(response => {
    titles.value = response.data.data

  })
      .catch(
          error => {
            console.error('<UNK>:', error)
            alert('<UNK>')
          }
      )
})
</script>    